package com.gitee.andy.rpc.entity;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class RpcResult {

	private Throwable error;
	private Object result;

	private Lock lock = new ReentrantLock();

	private Condition finishCondition = lock.newCondition();

	private long seq;

	public RpcResult(long seq) {
		this.seq = seq;
	}

	public Object getResult() throws Throwable {
		try {
			lock.lock();
			finishCondition.await(10, TimeUnit.SECONDS);
			if (error != null) {
				throw error;
			}
			return result;
		} finally {
			lock.unlock();
		}
	}

	public void setResult(RpcResponse resp) {
		try {
			lock.lock();
			if (resp.getError() != null) {
				error = resp.getError();
			} else {
				this.result = resp.getResult();
			}
			finishCondition.signal();
		} finally {
			lock.unlock();
		}
	}

}
